<template>
  <div class="schedule-add">
    <div class="schedule-form">
      <el-form :model="form" label-width="100px">
        <div class="form-row">
          <el-form-item label="排班月份">
            <el-select v-model="form.yearMonth" placeholder="请选择月份" class="custom-select" @change="handleMonthChange">
              <el-option v-for="item in monthOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="上/下半月">
            <el-select v-model="form.halfMonth" placeholder="请选择上/下半月" class="custom-select"
              @change="handleHalfMonthChange">
              <el-option label="上半月" value="first" />
              <el-option label="下半月" value="second" />
            </el-select>
          </el-form-item>
          <el-form-item label="护士姓名">
            <el-select v-model="form.nurse" placeholder="请选择护士" class="custom-select" @change="handleNurseChange">
              <el-option v-for="item in nurseOptions" :key="item.nurseCode" :label="item.name"
                :value="item.nurseCode" />
            </el-select>
          </el-form-item>
        </div>
      </el-form>

      <div class="schedule-grid">
        <div v-for="(day, index) in scheduleData" :key="index" class="schedule-row">
          <div class="schedule-cell">
            <div class="day-number">{{ day.number }}号</div>
            <div class="day-name">{{ day.weekday }}</div>
            <div class="shift-options">
              <el-radio-group v-model="day.shift">
                <el-radio label="早班">早班</el-radio>
                <el-radio label="中班">中班</el-radio>
                <el-radio label="晚班">晚班</el-radio>
                <el-radio label="休息">休息</el-radio>
              </el-radio-group>
            </div>
          </div>
        </div>
      </div>

      <div class="form-footer">
        <el-button type="primary" size="large" @click="handleSubmit">添加排班</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import { getCurrentInstance } from 'vue';
import router from '@/router';

onMounted(() => {
  getNurses()
})

// 获取当前实例
const { proxy } = getCurrentInstance();

const form = reactive({
  yearMonth: '',  // 年月
  halfMonth: '',  // 上/下半月
  nurse: '',      // 护士
  nurseName: ''   // 护士姓名
})

// 生成月份选项（未来12个月）
const generateMonthOptions = () => {
  const options = []
  const currentDate = dayjs()

  for (let i = 0; i < 12; i++) {
    const date = currentDate.add(i, 'month')
    const value = date.format('YYYY-MM')
    const label = date.format('YYYY年MM月')
    options.push({ value, label })
  }

  return options
}

const monthOptions = generateMonthOptions()
const nurseOptions = ref([])

const getNurses = () => {
  proxy.http.get("/api/WorkforceController/GetNurseList").then(res => {
    if (!res) {
      ElMessage.error(res?.message || '获取护士列表失败')
      nurseOptions.value = []
      return
    }
    nurseOptions.value = res.data
  }).catch(err => {
    console.error('获取护士列表错误:', err)
    ElMessage.error('获取护士列表失败：' + (err.message || '未知错误'))
    nurseOptions.value = []
  })
}

// 生成排班数据
const generateScheduleData = (yearMonth, halfMonth) => {
  if (!yearMonth || !halfMonth) return []

  const [year, month] = yearMonth.split('-')
  const daysInMonth = dayjs(`${year}-${month}`).daysInMonth()
  const scheduleData = []

  // 确定开始和结束日期
  let startDay = halfMonth === 'first' ? 1 : 16
  let endDay = halfMonth === 'first' ? 15 : daysInMonth

  for (let i = startDay; i <= endDay; i++) {
    const date = dayjs(`${year}-${month}-${i}`)
    scheduleData.push({
      number: i,
      weekday: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.day()],
      shift: ''
    })
  }

  return scheduleData
}

const scheduleData = ref([])

// 监听月份和上下半月变化
const handleMonthChange = () => {
  if (form.halfMonth) {
    scheduleData.value = generateScheduleData(form.yearMonth, form.halfMonth)
  }
}

const handleHalfMonthChange = () => {
  if (form.yearMonth) {
    scheduleData.value = generateScheduleData(form.yearMonth, form.halfMonth)
  }
}

// 添加排班规则验证方法
const validateScheduleRules = (scheduleData) => {
  // 获取所有已排班的数据并按日期排序
  const scheduledDays = scheduleData
    .filter(day => day.shift)
    .sort((a, b) => a.number - b.number)

  if (scheduledDays.length === 0) {
    return { valid: false, message: '请至少安排一个班次' }
  }

  // 按周分组排班数据
  const weekGroups = {}
  scheduledDays.forEach(day => {
    const date = dayjs(`${form.yearMonth}-${day.number}`)
    const weekKey = date.startOf('week').format('YYYY-MM-DD')

    if (!weekGroups[weekKey]) {
      weekGroups[weekKey] = []
    }
    weekGroups[weekKey].push({
      ...day,
      date: date
    })
  })

  // 检查每周是否有夜班
  for (const [weekStart, days] of Object.entries(weekGroups)) {
    const hasNightShift = days.some(day => day.shift === '晚班')
    if (!hasNightShift) {
      const weekDate = dayjs(weekStart)
      return {
        valid: false,
        message: `${weekDate.format('MM.DD')}这周未安排晚班，每周必须安排一次晚班`
      }
    }
  }

  // 检查晚班后是否直接排早班
  for (let i = 0; i < scheduledDays.length - 1; i++) {
    const currentDay = scheduledDays[i]
    const nextDay = scheduledDays[i + 1]

    // 检查是否是连续的两天
    const currentDate = dayjs(`${form.yearMonth}-${currentDay.number}`)
    const nextDate = dayjs(`${form.yearMonth}-${nextDay.number}`)
    const isConsecutiveDays = nextDate.diff(currentDate, 'day') === 1

    if (isConsecutiveDays && currentDay.shift === '晚班' && nextDay.shift === '早班') {
      return {
        valid: false,
        message: `${currentDay.number}号晚班后不能直接安排${nextDay.number}号早班`
      }
    }
  }

  // 检查每天是否只安排了一个班次
  const dayShiftCount = {}
  scheduledDays.forEach(day => {
    if (!dayShiftCount[day.number]) {
      dayShiftCount[day.number] = 0
    }
    dayShiftCount[day.number]++
  })

  for (const [day, count] of Object.entries(dayShiftCount)) {
    if (count > 1) {
      return {
        valid: false,
        message: `${day}号被安排了多个班次，每天只能安排一个班次`
      }
    }
  }

  return { valid: true }
}

// 获取路由参数值转换为stage
const getStageValue = (halfMonth) => {
  return halfMonth === 'first' ? 1 : 2
}

// 根据day值判断上半月还是下半月
const getHalfMonthFromDay = (day) => {
  return parseInt(day) <= 15 ? 'first' : 'second'
}

// 修改提交方法
const handleSubmit = async () => {
  if (!form.yearMonth || !form.halfMonth || !form.nurse) {
    ElMessage.warning('请填写完整信息')
    return
  }

  try {
    // 验证排班规则
    const validation = validateScheduleRules(scheduleData.value)
    if (!validation.valid) {
      ElMessage.warning(validation.message)
      return
    }

    // 获取选中护士的名字
    const selectedNurse = nurseOptions.value.find(n => n.nurseCode === form.nurse)

    // 构造排班数据
    const workforceData = scheduleData.value
      .filter(day => day.shift)
      .map(day => ({
        Year: parseInt(form.yearMonth.split('-')[0]),
        Month: parseInt(form.yearMonth.split('-')[1]),
        Stage: day.number.toString(),  // Stage仍然使用日期
        NurseCode: form.nurse,
        NurseName: selectedNurse?.name || '',
        WorkDate: `${form.yearMonth}-${day.number.toString().padStart(2, '0')}`,
        WorkWeek: dayjs(`${form.yearMonth}-${day.number}`).format('YYYY-MM-DD HH:mm:ss'),
        ClassGroup: day.shift,
        Creator: "当前用户名",
        CreateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
      }))

    console.log('提交排班数据:', workforceData)

    const response = await proxy.http.post("/api/WorkforceController/AddWorkforces", workforceData)
    if (!response || !response.status) {
      ElMessage.error(response?.message || '添加排班失败')
      return
    }
    
    ElMessage.success('添加排班成功')
    resetForm()
    router.push('/WorkforceManagementList')
  } catch (error) {
    console.error('添加排班出错：', error)
    ElMessage.error('添加排班失败：' + (error.message || '未知错误'))
  }
}

// 重置表单方法
const resetForm = () => {
  form.yearMonth = ''
  form.halfMonth = ''
  form.nurse = ''
  scheduleData.value = []
}

// 监听护士选择变化
const handleNurseChange = (value) => {
  const nurse = nurseOptions.value.find(n => n.nurseCode === value)
  if (nurse) {
    form.nurseName = nurse.name
  }
}
</script>

<style scoped>
.schedule-add {
  padding: 20px;
}

.schedule-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.schedule-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
  margin-top: 20px;
}

.schedule-cell {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.day-number {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.day-name {
  color: #666;
  margin-bottom: 10px;
}

.shift-options .el-radio {
  margin-right: 10px;
  margin-bottom: 5px;
}

.form-footer {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.form-footer .el-button {
  min-width: 120px;
  padding: 12px 30px;
}

.form-row {
  display: flex;
  justify-content: flex-start;
  gap: 20px;
  padding: 0 20px;
}

.custom-select {
  width: 200px !important;
}

.el-form-item {
  margin-bottom: 20px;
  margin-right: 0;
}
</style>